package com.css.bjdt_report.executive;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nutz.dao.Sqls;

import com.css.bjdt_report.cell.entity.Cell;
import com.css.bjdt_report.cell.entity.VarParam;
import com.css.bjdt_report.cell.service.CellDataService;
import com.css.bjdt_report.executive.report.ReportSession;
import com.css.bjdt_report.util.spring.SpringContextHolder;

public class SqlExecutor extends DefaultExecutor {

	private CellDataService cellDataService = SpringContextHolder.getBean(CellDataService.class);

	private static Log logger = LogFactory.getLog(SqlExecutor.class);

	@Override
	public String execute(Cell cell, ReportSession session) {
		if (logger.isDebugEnabled())
			logger.debug("executeSql cell id=" + cell.getCellId());
		List<VarParam> varparams = new ArrayList<VarParam>();
		VarParam unitParam = new VarParam(null, null, "unitConditionVal", (String) session.get(ReportSession.REPORT_CACHE, "unit"));
		VarParam startTimeParam = new VarParam(null, null, "startTimeConditionVal", (String) session.get(ReportSession.REPORT_CACHE, "startTime"));
		VarParam endTimeParam = new VarParam(null, null, "endTimeConditionVal", (String) session.get(ReportSession.REPORT_CACHE, "endTime"));
		varparams.add(unitParam);
		varparams.add(startTimeParam);
		varparams.add(endTimeParam);
		String result = "0";
		if (cell.getSqlExp() != null) {
			try {
				result = cellDataService.executeSql(cell.getSqlExp(), Sqls.callback.str(), varparams.toArray(new VarParam[0])).getString();
			} catch (Exception e) {
				logger.debug("error sql is " + cell.getSqlExp(), e);
			}
		}
		return result;
	}

}
